import path from "@/framework/util/path.ts";
import { showMessageAndPrint } from "@/framework/util/log.ts";

export function getPlatform() {
  return native.process.platform === "win32" ? "win" : native.process.platform;
}

export function getBitness() {
  return native.process.arch === "ia32" || native.process.arch === "arm" ? 32 : 64;
}

export interface OpenInTerminalOptions {
  /**
   * 要添加到Path变量的子目录
   */
  subPath?: string[];
  /**
   * 其他环境变量
   */
  env?: Record<string, string | undefined>;
}

/**
 * 开终端并定位到指定目录
 * @param cwd
 * @param opts
 */
export function openInTerminal(cwd: string, opts?: OpenInTerminalOptions) {
  const pathVar: string[] = [];
  if (opts?.subPath) {
    pathVar.push(...opts.subPath.map(sub => path.join(cwd, sub)));
  }
  pathVar.push(native.process.env.Path! || native.process.env.PATH!);
  const env = {
    ...native.process.env,
    ...opts?.env,
    PATH: pathVar.join(path.delimiter),
  };

  native.cp.execCmd(`cmd.exe /c start cmd.exe`, { cwd, env }).catch(showMessageAndPrint);
}

export interface ExecInTerminalOpts extends OpenInTerminalOptions {
  /**
   * 当前工作目录
   */
  cwd?: string;
  /**
   * 以管理员身份执行
   */
  sudo?: boolean;
  /**
   * 保持窗口(增加"cmd /k")
   * @default true
   */
  keep?: boolean;
}

/**
 * 打开系统终端并执行命令
 * @param cmd 要执行的命令
 * @param opts
 */
export function execInTerminal(cmd: string, opts?: ExecInTerminalOpts) {
  const pathVar: string[] = [];
  if (opts?.cwd && opts?.subPath) {
    pathVar.push(...opts.subPath.map(sub => path.join(opts.cwd, sub)));
  }
  pathVar.push(native.process.env.Path! || native.process.env.PATH!);
  const env = {
    ...native.process.env,
    ...opts?.env,
    PATH: pathVar.join(path.delimiter),
  };
  const k = opts?.keep ?? true;
  (opts?.sudo ? native.cp.execCmdSudo : native.cp.execCmd)(`cmd /c start ${k ? "cmd /k" : ""} ${cmd}`, {
    cwd: opts?.cwd,
    env,
  }).catch(showMessageAndPrint);
}

/**
 * 获取文件图标base64
 * @param file 文件路径
 */
export async function getFileIconBase64(file: string): Promise<string> {
  const icon = await native.ipc.invokeNode("electron.app.getFileIcon", file, { size: "small" });
  return icon.toDataURL();
}
